package web;

import domain.Users;
import service.User_Service;
import service.impl.User_ServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置页面编码
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        //实例化session对象
        HttpSession session = request.getSession();
        //校验验证嘛
        String verifycode = request.getParameter("verifycode");
        System.out.println("填写的验证码："+verifycode);
        String code =(String) session.getAttribute("code");
/*        if (!code.equalsIgnoreCase(verifycode))
        {
           //验证码错误
            request.setAttribute("error","验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }*/


        //获取输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        //调用User_Service查询
        User_Service user_service = new User_ServiceImpl();
        Users user_login =  user_service.userLogin(username,password);
        System.out.println(user_login);
        if (user_login != null){
            session.setAttribute("project_id",user_login.getProject_id());
            session.setAttribute("username",user_login.getUsername());
            switch (user_login.getRole())
            {
                case "admin":
                    request.getRequestDispatcher("adminServlet").forward(request,response);
                    break;
                case "user":
                    /*request.getRequestDispatcher("userServlet").forward(request,response);*/
                    response.sendRedirect("userServlet");
                    break;
                case "editor":
                    response.sendRedirect("editorServlet");
                    //request.getRequestDispatcher("editor.jsp").forward(request,response);
                    break;
                default:
                    request.setAttribute("error","非法用户");
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                    break;
            }
        }else {
            request.setAttribute("error","用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
